//const frameurl = 'http://thinktest/test.html'
//const posturl = 'http://thinktest/api/Test/'
const posturl = 'http://127.0.0.1:2346/'
const frameurl = 'http://127.0.0.1:2346/test.html'

function getFrame() {
  var iframe = document.createElement('iframe')
  iframe.style.width = '0'
  iframe.style.height = '0'
  iframe.isload = false

  iframe.setAttribute('src', frameurl)
  iframe.onload = function () {
    iframe.isload = true
  }
  document.body.appendChild(iframe)

  function parsemsg(event) {
    console.log(event.origin)
    const message = event.data
    let res = JSON.parse(message)
    var result = { type: 'success', data: {}, info: res }
    if (res.status == 200) result.data = res.data
    else if (res.status == 300) result.type = 'redirect'
    else result.type = 'error'
    return result
  }

  iframe.sending = (url = '', params = {}, type = 'get') => {
    return new Promise((resolve, reject) => {
      var handleMessage = (event) => {
        resolve(parsemsg(event))
        window.removeEventListener('message', handleMessage)
      }
      window.addEventListener('message', handleMessage)

      try {
        var data = { type: type, url: posturl + url, data: params }
        iframe.contentWindow.postMessage(JSON.stringify(data), '*')
      } catch (e) {
        reject(e)
      }
    })
  }
  return iframe
}

const iframe = getFrame()

export default iframe
